package com.xgg.taiwuinfo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xgg.taiwuinfo.adapter.FCAdapter;
import com.xgg.taiwuinfo.adapter.SpinAdapter;
import com.xgg.taiwuinfo.filter.Filter;
import com.xgg.taiwuinfo.filter.FilterComponent;
import com.xgg.taiwuinfo.filter.FilterList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class FilterDetailActivity extends AppCompatActivity {

    int mId;
    //这个是核心数据，来自于全局静态变量，注意是引用，不点击保存不修改
    Filter mFilter;
    ListView list_fc;
    FCAdapter mAdapter;
    List<Map<String, String>> mMap = new ArrayList<>();
    ArrayList<FilterComponent> mTempList = new ArrayList<>();
    TextView txt_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filterdetail);
        Intent intent = getIntent();
        try
        {
            mId = intent.getExtras().getInt("id");
            mFilter = FilterList.getList().get(mId);
            FilterComponent.setHandler(mHandler);
        }
        catch (Exception e)
        {
            Toast.makeText(this, "获取过滤器失败", Toast.LENGTH_LONG).show();
            finish();
        }
        list_fc = findViewById(R.id.list_fc);
        mAdapter = new FCAdapter(this ,0 ,null,null);

        list_fc.setAdapter(mAdapter);
        txt_name = findViewById(R.id.txt_name);
        txt_name.setText(mFilter.mName);
        //开始获取数据
        UpdateAllData();
        //功法基本属性
        AddMap(mMap , "功法类型" , FilterComponent.FT_TYPE_EQUAL_SELECT + "");
        AddMap(mMap , "功法五行" , FilterComponent.FT_ElEMENT_EQUAL_SELECT + "");
        AddMap(mMap , "功法门派" , FilterComponent.FT_INHERIT_EQUAL_SELECT + "");
        AddMap(mMap , "功法品级" , FilterComponent.FT_LEVEL_COMP_SELECT + "");
        AddMap(mMap , "功法占用格子" , FilterComponent.FT_GRIDOCCUPY_COMP_SELECT + "");
        AddMap(mMap , "功法名称" , FilterComponent.FT_NAME_CONTAIN_EDIT + "");
        //运功效果
        AddMap(mMap , "施法参数" , FilterComponent.FT_CAST_COMAPRE_NUM + "");
        AddMap(mMap , "运功效果-行动能力" , FilterComponent.FT_YUNGONG_ACTOIN_COMPARE_NUM + "");
        AddMap(mMap , "运功效果-攻击发挥" , FilterComponent.FT_YUNGONG_ATTACK_COMPARE_NUM + "");
        //各种专门分类
        AddMap(mMap , "内功-格子分布" , FilterComponent.FT_NEIGONGGRID + "");
        AddMap(mMap, "摧破-攻击部位" , FilterComponent.FT_CUIPOBODY_EQUAL_SELECT + "");
        AddMap(mMap, "摧破-伤害" , FilterComponent.FT_DAMAGE_COMPARE_NUM + "");
        AddMap(mMap, "摧破-发挥点穴及破绽效果" , FilterComponent.FT_CUIPOEFFECT_COMPARE_SELECT + "");
        AddMap(mMap, "摧破-命中加成", FilterComponent.FT_HIT_COMPARE_NUM + "");
        AddMap(mMap, "摧破-发挥分布", FilterComponent.FT_CUIPOHIT_COMPARE_SELECT + "");
    }

    void UpdateAllData()
    {
        mAdapter.m_fclist.clear();
        for(FilterComponent  fc :mFilter.mList) {
            mAdapter.m_fclist.add(fc);
        }
        for(FilterComponent  fc : mTempList) {
            mAdapter.m_fclist.add(fc);
        }
        mAdapter.notifyDataSetChanged();
    }

    void UpdateAddingTail(FilterComponent newfc)
    {
        mTempList.add(newfc);
        mAdapter.m_fclist.add(newfc);
        mAdapter.notifyDataSetChanged();
    }

    void UpdateDelete(FilterComponent delfc)
    {
        if (mAdapter.m_fclist.remove(delfc))
            mAdapter.notifyDataSetChanged();
        mTempList.remove(delfc);
    }

    void DiscardAll()
    {
        //先恢复名字
        txt_name.setText(mFilter.mName);
        mFilter.mTempName = mFilter.mName;
        //若有新增的fc，删除
        mTempList.clear();
        //若有修改的fc，恢复
        for (FilterComponent fc : mFilter.mList)
        {
            fc.discard();
        }
    }

    Handler mHandler = new Handler(new Handler.Callback(){
        @Override
        //书写handleMessage方法，用于第三步接收并处理信息
        public boolean handleMessage(Message msg) {
        if (msg.what == FilterComponent.MSG_DELETE){
            UpdateDelete((FilterComponent)msg.obj);
        }
        return true;
        }
    });

    @Override
    public boolean onKeyDown(final int keyCode , final KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            //判断下是否被修改过了
            Boolean edited = isEdited();
            if (!edited)
            {
                return super.onKeyDown(keyCode, event);
            }

            AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle("确定不保存就退出吗？")
                .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    DiscardAll();
                    FilterDetailActivity.this.finish();
                    }
                })
                .setNegativeButton("再看看", null)
                .create();
            alertDialog.show();
            return false;
        }
        else if (keyCode == KeyEvent.KEYCODE_MENU)
        {
            return false;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }
    }

    boolean isEdited()
    {
        if (mTempList.size() > 0)
            return true;
        if (mFilter.mList.size() != mAdapter.m_fclist.size())
            return true;
        for (FilterComponent fc :mFilter.mList) {
            if (fc.isEdited())
            {
                return true;
            }
        }
        if (!txt_name.getText().toString().equals(mFilter.mName))
            return true;
        return false;
    }

    void AddMap(List<Map<String, String>> list , String field , String value)
    {
        Map<String, String> map = new HashMap<>();
        map.put("f", field);
        map.put("v", value);
        list.add(map);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater in = getMenuInflater();
        in.inflate(R.menu.filtermenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save:
                mFilter.mList = mAdapter.m_fclist;
                mFilter.save();
                FilterList.SaveToSP(this);
                finish();
                break;
            case R.id.menu_editname:
                final EditText et = new EditText(this);
                et.setText(mFilter.mTempName);
                et.setMaxLines(1);
                AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("编辑名称")
                    .setView(et)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        String str = et.getText().toString();
                        if (str.length() > 0)
                        {
                            if (FilterList.DupName(str)) {
                                mFilter.mTempName = str;
                                txt_name.setText(str);
                            }
                            else {
                                Toast.makeText(FilterDetailActivity.this , "与现有名字重复" , Toast.LENGTH_LONG).show();
                            }
                        }
                        }
                    })
                    .setNegativeButton("取消",null)
                    .create();
                alertDialog.show();
                break;
            case R.id.menu_discard:
                DiscardAll();
                UpdateAllData();
                break;
            case R.id.menu_addfc:
                AlertDialog newfcdiag = new AlertDialog.Builder(this)
                    .setTitle("选择过滤条件类型")
                    .setAdapter(new SpinAdapter(FilterDetailActivity.this , R.layout.item_spin , mMap), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                        int typeid = Integer.parseInt(mMap.get(i).get("v"));
                        FilterComponent newfc = FilterComponent.LoadJson(null , typeid , FilterDetailActivity.this);
                        if (newfc != null)
                            UpdateAddingTail(newfc);
                        }
                    })
                    .create();
                newfcdiag.show();
                break;
            case R.id.menu_delete:
                AlertDialog deleteDialog = new AlertDialog.Builder(this)
                    .setTitle("确定删除这个过滤器吗？")
                    .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (FilterList.DeleteFilter(mFilter)) {
                                FilterList.SaveToSP(FilterDetailActivity.this);
                                FilterDetailActivity.this.finish();
                            }
                            else{
                                Toast.makeText(FilterDetailActivity.this, "不能删除最后一个过滤器" , Toast.LENGTH_LONG).show();
                            }
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
                deleteDialog.show();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return super.onOptionsItemSelected(item);
    }
}
